package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.Utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }


    /**
     * 获取入住列表
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCheckIn(CheckInApplyDto dto) {
        //这个一的那个是新增,而新增接口,只需要考虑一件事:就是数据库里的字段要咋样填充进去
        //检验老人是否入住
        //sql: select * from check_in where elder_id = ? ;
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder != null && elder.getStatus() == 1) {
            //说明已经有这个老人入住了
            throw new RuntimeException("该老头已入住");
        }

        //更新床位状态为已入住
        //sql: update bed set status = 1 where id = ?
        /*
         * bedService.lambdaUpdate()
         * .set(Bed::getStatus,1)
         * .eq(Bed::getId,dto.getCheckInConfigDto().getBedId())
         * .update();
         *
         * */
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(dto.getCheckInConfigDto().getBedId());
        bedService.updateById(bed);
        //根据bedid查询bed
        Bed dbBed = bedService.getById(dto.getCheckInConfigDto().getBedId());
        if (dbBed == null) {
            throw new RuntimeException("该床位不存在");
        }

        //新增或更新老人
//        if(elder==null){
//            //没老人
//            Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
//            newElder.setBedId(dbBed.getId());
//            newElder.setStatus(1);
//            newElder.setBedNumber(dbBed.getBedNumber());
//            elderService.save(newElder);
//        }else {
//            Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
//            newElder.setBedId(dbBed.getId());
//            newElder.setStatus(1);
//            newElder.setBedNumber(dbBed.getBedNumber());
//            elderService.updateById(newElder);
//        }
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newElder.setBedId(dbBed.getId());
        newElder.setStatus(1);
        newElder.setBedNumber(dbBed.getBedNumber());
        if (elder != null) {
            newElder.setId(elder.getId());
        }
        elderService.saveOrUpdate(newElder);


        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        //生成合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //根据开始时间和当前时间做对比 判断是否入住
        contract.setStatus(LocalDateTime.now().isAfter(startDate) ? 1 : 0);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(newElder.getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(dbBed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//约定好把家属信息的json存到remark
        this.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);

    }


    /**
     * 获取申请入住详细信息
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //查看申请入住详情
        // 需要先查到入住表信息
        //sql:select * from check_in where id =?;
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null) {
            throw new RuntimeException("该入住信息不存在");
        }
        //开始查看老人信息表
        Elder elder = elderService.getById(checkIn.getElderId());
        if (elder == null) {
            throw new RuntimeException("该老人信息不存在");
        }
        //计算年龄
        int age=0;
        String idCardNo = elder.getIdCardNo();
        if(idCardNo!=null && idCardNo.length()>=18){
            //获取身份证的出生年月日
            String birthStr = idCardNo.substring(6, 14);
            int birthYear = Integer.parseInt(birthStr.substring(0, 4));
            int birthMonth = Integer.parseInt(birthStr.substring(4, 6));
            int birthDay = Integer.parseInt(birthStr.substring(6, 8));
            LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
            age = Period.between(birthDate, LocalDate.now()).getYears();
        }



        // 4. 查询老人家庭信息
        // 从CheckIn表的remark字段中获取家属信息（JSON格式）
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        if (remark != null && !remark.isEmpty()) {
            // 将JSON字符串转换为List<ElderFamilyVo>
            elderFamilyVoList = JSONUtil.toList(JSONUtil.parseArray(remark), ElderFamilyVo.class);
        }


        //入住配置信息
        //sql:select * from check_in_config where check_in_id = ?;
        CheckInConfig config = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id)
                .one();

        //签约办理合同信息
        //sql:select * from contract where elder_id=?
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();


        //将查到的结果进行封装
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(BeanUtil.toBean(elder, CheckInElderVo.class));
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(BeanUtil.toBean(config, CheckInConfigVo.class));
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
